package com.zyong.design.pattern.responsibility.case5;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @program: zyong-design-pattern
 * @ClassName: VerifyHandlerChain
 * @author: zyong
 * @create: 2024-04-13 19:45
 */
@Component
public class VerifyHandlerChain implements InitializingBean, ApplicationContextAware {
    private ApplicationContext applicationContext;
    private List<VerifyHandler> verifyHandlers;

    @Override
    public void afterPropertiesSet() throws Exception {
        applicationContext.getBeansOfType(VerifyHandler.class).values().forEach(verifyHandler -> {
            if (verifyHandlers == null) {
                verifyHandlers = new ArrayList<>();
            }
            verifyHandlers.add(verifyHandler);
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public List<Object> verifyAll(List<Object> allObjectList) {
        if (CollectionUtils.isEmpty(verifyHandlers)) {
            return Collections.emptyList();
        }

        List<Object> resultList = new ArrayList<>();
        for (VerifyHandler verifyHandler : verifyHandlers) {
            resultList = verifyHandler.verify(allObjectList);
        }

        return resultList;
    }
}
